package com.tanhua.server.api.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.AdminMapper;
import com.tanhua.common.pojo.Admin;
import com.tanhua.server.api.AdminService;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Value("${jwt.secret}")// 盐值
    private String secret;
    @Autowired
    private AdminMapper adminMapper;


    /**
     * 根据token查询用户
     *
     * @param token
     * @return
     */
    public Admin queryAdminByToken(String token) {
        //
        if (ObjectUtil.isEmpty(token)) {
            return null;
        }
        // 前端传过来的token需要去掉前缀
        String replace = token.replace("Bearer ", "");
        Map<String, Object> body = Jwts.parser().setSigningKey(secret).parseClaimsJws(replace).getBody();
        if (ObjectUtil.isEmpty(body)) {
            return null;
        }
        Long id = Long.valueOf(body.get("id").toString());
        Admin admin = adminMapper.selectById(id);
        return admin;
    }

    /**
     * 根据用户名和密码去数据库查询用户
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public Admin selectByUsernameAndPassword(String userName, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        Map<String, String> map = new HashMap<>();
        String s = SecureUtil.md5(password);
        map.put("username", userName);
        map.put("password", s);
        queryWrapper.allEq(map);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }
}
